﻿using SF.Common;
using SF.Ucenter.shallWeChat;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;

namespace SF.Ucenter.mall
{
    public partial class index : System.Web.UI.Page
    {
        protected string usingMsg="", jsMsg="", htmlMsg="";
        protected void Page_Load(object sender, EventArgs e)
        {
            #region 测试代码
            string openIdT = "oKgsLwi-xugB0Y9XDDM84zpa65_I";
            //根据openid获取当前微信端的 用户对象
            BLL.sf_user_info userBllT = new BLL.sf_user_info();
            Model.sf_user_info user_infoT = new Model.sf_user_info();
            user_infoT = userBllT.GetModelByOpenId(openIdT);

            //对 用户对象 昵称、头像 赋值
            //user_info.nickName = p1.nickname;
            //user_info.photoUri = p1.headimgurl;
            //user_info.province = p1.province;
            //user_info.city = p1.city;

            Session[DTKeys.SESSION_ADMIN_INFO] = user_infoT;
            Session.Timeout = 45;
            //写入登录日志
            //Model.siteconfig siteConfig = new BLL.siteconfig().loadConfig();
            //bool isup = userBllT.Update(user_infoT);
            loading();

            return;
            #endregion

            #region Oauth授权获取到用户信息
            api.wxpay.WebClient obj = new api.wxpay.WebClient();
            //获取配置的请求参数
            IDictionary dict = ConfigurationManager.GetSection("weixinPay") as IDictionary;
            string reluri = Server.UrlEncode(dict["ip_url"].ToString() + "/mall/index.aspx");
            string code_uri = dict["code_uri"].ToString();
            string openid_uri = dict["openid_uri"].ToString();
            string user_uri = dict["user_uri"].ToString();
            string temp_uri = dict["temp_uri"].ToString();
            string qrcode_uri = dict["qrcode_uri"].ToString();
            string inf_uri = dict["inf_uri"].ToString();
            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["code"]))
                {
                    string appNum = string.IsNullOrEmpty(Request.QueryString["state"].ToString()) ? Request["state"] : Request.QueryString["state"];
                    Model.sf_appidmanage appModel = new BLL.sf_appidmanage().GetModel(appNum);
                    string appSecret = appModel != null ? appModel.appsecret : "";
                    string str = obj.GetHtml(string.Concat(openid_uri, "appid=", appNum, "&secret=", appSecret, "&code=", Request.QueryString["code"], "&grant_type=authorization_code"));
                    code2openid p = api.wxpay.JsonHelper.JsonDeserialize<code2openid>(str);
                    string str2 = obj.GetHtml(string.Concat(user_uri, "access_token=" + p.access_token + "&openid=" + p.openid + "&lang=zh_CN"));
                    userinfo p1 = api.wxpay.JsonHelper.JsonDeserialize<userinfo>(str2);
                    //根据openid获取当前微信端的 用户对象
                    BLL.sf_user_info userBll = new BLL.sf_user_info();
                    Model.sf_user_info user_info = new Model.sf_user_info();
                    user_info = userBll.GetModelByOpenId(p.openid);

                    //对 用户对象 昵称、头像 赋值
                    user_info.nickName = p1.nickname;
                    user_info.photoUri = p1.headimgurl;
                    user_info.province = p1.province;
                    user_info.city = p1.city;

                    Session[DTKeys.SESSION_ADMIN_INFO] = user_info;
                    Session.Timeout = 45;
                    //写入登录日志
                    Model.siteconfig siteConfig = new BLL.siteconfig().loadConfig();
                    bool isup = userBll.Update(user_info);
                    loading();

                    if (!System.IO.File.Exists(Common.Utils.GetMapPath("/allqrcode/code/" + user_info.inviteKey + ".jpg")))
                    {

                        //获取微信接口的access_token
                        string str3 = obj.GetHtml(inf_uri + "grant_type=client_credential&appid=" + appNum + "&secret=" + appSecret);
                        wxaccesstoken ak = api.wxpay.JsonHelper.JsonDeserialize<wxaccesstoken>(str3);

                        //获取 二维码 对象  用于换取 二维码资源 链接
                        string str4 = obj.Post(temp_uri + "access_token=" + ak.access_token, "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + user_info.inviteKey + "\"}}}");
                        shallWeChat.qrcode qr = api.wxpay.JsonHelper.JsonDeserialize<shallWeChat.qrcode>(str4);

                        /*通过ticket换二维码*/
                        string imgs = Server.UrlEncode(qr.ticket);
                        obj.DownloadFile(qrcode_uri + "ticket=" + imgs, Common.Utils.GetMapPath("/allqrcode/code/" + user_info.inviteKey + ".jpg"));
                    }
                }
                else
                {
                    string appNum = string.IsNullOrEmpty(Request.QueryString["appnum"].ToString()) ? Request["appnum"] : Request.QueryString["appnum"];
                    if (string.IsNullOrEmpty(appNum))
                    {
                        Response.Redirect("1.html");
                    }
                    //snsapi_base 请求Oauth所需code
                    string open = string.Concat(code_uri, "appid=", appNum, "&redirect_uri=", reluri, "&response_type=code&scope=snsapi_userinfo&state=" + appNum + "#wechat_redirect");
                    Response.Redirect(open, false);
                }
            }
            catch (Exception ex)
            {
            }
            #endregion
            //生成首页商品等html标签
            //BLL.sf_user_info uBll = new BLL.sf_user_info();
            //Model.sf_user_info userInfo = uBll.GetModel(1);
            //userInfo = userInfo == null ? uBll.GetModel(2) : userInfo;
            //Session[DTKeys.SESSION_ADMIN_INFO] = userInfo;
            //loading();
        }

        public void loading()
        {
            if (Session[DTKeys.SESSION_ADMIN_INFO] as Model.sf_user_info != null)
            {
                Model.sf_user_info userinfo = Session[DTKeys.SESSION_ADMIN_INFO] as Model.sf_user_info;
                string templateType = new BLL.sf_modeconfig().GetModel("settingNum='" + userinfo.templatesNum + "'").call_encoding;
                SF.Web.UI.mallCs.index loadIndex = new Web.UI.mallCs.index();
                usingMsg = loadIndex.loaddingUsing(userinfo, templateType);  //加载界面css及js文件（无需改动）
                jsMsg = loadIndex.loaddingJs(userinfo, templateType);  //加载javaScript函数实现
                htmlMsg = loadIndex.loaddingHtml(userinfo, templateType);  //加载页面内容
            }
        }

    }
}